package com.test.redis.pool;

import java.time.Duration;
import java.util.Objects;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisConnectionPoolUtil {
    private static JedisPool pool;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        //最大连接数
        config.setMaxTotal(100);
        //最大空闲连接数
        config.setMaxIdle(50);
        //最小空闲连接数
        config.setMinIdle(10);
        //获取连接时的最大等待时间，单位毫秒
        config.setMaxWait(Duration.ofMillis(1000));
        //获取连接时是否对连接进行有效性校验
        config.setTestOnBorrow(true);

        pool = new JedisPool(config,"localhost",6379);
    }

    /**
     * 获取Jedis实例
     */
    public static Jedis getJedis(){
        return pool.getResource();
    }

    /**
     * 关闭Jedis实例
     * @param jedis
     */
    public static void close(Jedis jedis){
        if(Objects.nonNull(jedis)){
            jedis.close();
        }
    }

    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.ping());
        String key = "testKey";
        jedis.set(key,"Hello World Redis!");
        String value = jedis.get(key);
        System.out.println(value);
        close(jedis);
    }
}
